// 观察者
// 负责：知道页面哪些地方用到某个数据
// 通过发布者通知，watcher 进行页面更新
import { Dep } from './dep.js'
import CompileUtil from './utils/compileUtil.js'

export class Watcher {

  constructor(vm, expr, cb) {
    Dep.target = this
    this.vm = vm
    this.expr = expr
    this.cb = cb

    //默认先存放旧值
    this.oldValue = this.get()
    //添加 Watcher 对象到发布者后清空，防止每次获取数据都添加 Watcher 到发布者
    Dep.target = null
  }

  get() {
    let value = CompileUtil.getVal(this.vm, this.expr)
    return value
  }

  update() {
    let newValue = CompileUtil.getVal(this.vm, this.expr)
    if (newValue !== this.oldValue) {
      this.cb(newValue)
    }
  }
}